<?php

namespace App\Models;

use App\Libraries\Thread;
use App\Models\ComModel;
use App\Models\NoticeModel;

class CronModel extends ComModel
{
    // 入队任务
    /*
     * type 类型  notice
     *
     */
    public function add_cron($type, $data)
    {
        $data = esc($data);
        $this->db->table('cron')->insert([
            'type' => $type,
            'value' => json_encode($data),
            'status' => 0,
            'error' => '',
            'updatetime' => 0,
            'inputtime' => time(),
        ]);
        $id = $this->db->insertID();
        if ($id) {
            $thread = new Thread();
            // 运行任务
            $thread->cron(['action' => 'cron', 'id' => $id]);
            return ams_rt(0, 'ok', $id);
        }
        return ams_rt(1, 'error');
    }

    // 存储
    public function save_cron($cron, $data)
    {
        $data = esc($data);
        $cron = esc($cron);
        if ((!$data['value'] && !$data['error']) || $cron['status'] >= 9) {
            // 没有错 或者 超时 就删除记录
            $this->db->table('cron')->where('id', $cron['id'])->delete();
            return ams_rt(0, 'ok');
        } else {
            $this->db->table('cron')->where('id', $cron['id'])->update([
                'value' => json_encode($data['value']),
                'error' => json_encode($data['error']),
                'status' => $cron['status'] + 1,
                'updatetime' => time(),
            ]);
            return ams_rt(0, $cron['id'] . '#' . (is_array($data['error']) ? implode('、', $data['error']) : $data['error']), $cron);
        }
    }

    // 执行本任务
    public function do_cron($cron)
    {

        if (!$cron || !is_array($cron)) {
            return false;
        }

        switch ($cron['type']) {

            case 'notice':
                $noticeModel = new NoticeModel();
                // 通知消息
                $value = json_decode($cron['value'], true);
                list($error, $value) = $noticeModel->cron_notice($value);
                // 加入队列并执行
                return $this->save_cron($cron, [
                    'error' => $error,
                    'value' => $value,
                ]);
                break;
        }

    }

    // 执行本任务
    public function do_cron_id($id)
    {
        $cron = $this->db->table('cron')->where('id', intval($id))->get()->getRowArray();
        return $this->do_cron($cron);
    }

    // 运行脚本
    public function run_cron($num = 20)
    {

        $crons = $this->db->table('cron')->limit($num ?? 20)->get()->getResultArray();
        
        if (!$crons) {
            return 0;
        }

        $thread = new Thread();
        $iscdn = $this->request->getGet('iscdn');

        foreach ($crons as $cron) {
            if ($iscdn) {
                $this->do_cron($cron);
            } else {
                $thread->cron(['action' => 'cron', 'id' => $cron['id']]);
            }
        }

        // 遍历文件
        if ($fp = @opendir(WRITEPATH . 'authcode/')) {
            while (false !== ($file = readdir($fp))) {
                if ($file === '.' or $file === '..'
                    or $file[0] === '.'
                    or !@is_file(WRITEPATH . 'authcode/' . $file)) {
                    continue;
                }
                if (time() - filemtime(WRITEPATH . 'authcode/' . $file) > 3600 * 24) {
                    // 超过24小时删除
                    @unlink(WRITEPATH . 'authcode/' . $file);
                }
            }
            closedir($fp);
        }
        return count($crons);
    }

}
